package com.falm.picturebackend.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.falm.picturebackend.util.JWTUtil;

/**
 * @author Administrator
 */
@Component // 在容器中进行注册
public class LoginInterceptor implements HandlerInterceptor {
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        // 放行OPTIONS请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }

        String requestURI = request.getRequestURI();
        // 登录与注册接口放行
        if (requestURI.startsWith("/api/user/login") || requestURI.startsWith("/api/user/registry")) {
            return true;
        }

        // 放行knife4j文档接口
        if (requestURI.startsWith("/api/doc.html") || requestURI.startsWith("/api/swagger-resources")
            || requestURI.startsWith("/api/v2/api-docs") || requestURI.startsWith("/api/v3/api-docs")
            || requestURI.startsWith("/api/webjars") || requestURI.startsWith("/api/knife4j")) {
            return true;
        }

        String token = request.getHeader("token");
        if (JWTUtil.verifyJwt(token)) {
            return true;
        }
        logger.info("用户未登录");
        return false;
    }

}